package com.stmt.analytic.graph.algorithm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Function;

public class MemoryBasedGraph {


    private IdMapping idMapping;

    private AdjacencyMatrix adjacency;

    protected MemoryBasedGraph(IdMapping idMapping, AdjacencyMatrix adjacency) {
        this.idMapping = idMapping;
        this.adjacency = adjacency;
    }

    public static final MemoryBasedGraph from(Collection<String> vertices, Collection<Pair<String, String>> edges) {
        Objects.nonNull(vertices);
        Objects.nonNull(edges);
        IdMapping idMapping = new IdMapping(vertices.size());
        vertices.forEach(oid -> {
            idMapping.add(oid);
        });
        final int nodeCount = idMapping.nodeCount();

        ArrayList<Integer>[] both = new ArrayList[nodeCount];
        edges.forEach(edge -> {
            int src = idMapping.toMappedId(edge.fst);
            int dst = idMapping.toMappedId(edge.snd);
            if (null == both[src]) {
                both[src] = new ArrayList<>();
            }
            both[src].add(dst);
            if (null == both[dst]) {
                both[dst] = new ArrayList<>();
            }
            both[dst].add(src);
        });
        AdjacencyMatrix adjacency = new AdjacencyMatrix(both);
        return new MemoryBasedGraph(idMapping, adjacency);
    }

    public int nodeCount() {
        return idMapping.nodeCount();
    }

    public int neighborSize(int vid) {
        return adjacency.armBothSize(vid);
    }

    public AdjacencyMatrix getAdjacencyMatrix() {
        return adjacency;
    }

    public void forEachVertex(Function function) {
        final int nodeCount = idMapping.nodeCount();
    }

    public String toOriginalId(int vid) {
        return idMapping.toOriginalId(vid);
    }

}
